#include "CF.h"
#include "CF_WorkspaceWindow.h"

#include <QTreeWidgetItem>
#include <QMessageBox>
#include <QFileDialog>

#include "CF_WorkspaceManager.h"
#include "CF_NewWorkspaceDialog.h"

CF_WorkspaceWindow::CF_WorkspaceWindow(QWidget *parent)
	: CL_Widget(parent)
{
	ui.setupUi(this);

    m_toolBar = new QToolBar(this);
    m_toolBar->setObjectName(tr("workspaceToolBar"));
	ui.gridLayout->addWidget(m_toolBar,0,0,1,1);

	QPixmap iconNewWorkspace(tr(":/Icon/NewWorkspace"));
	QAction* actionNewWorkspace = m_toolBar->addAction(QIcon(iconNewWorkspace), tr("New Workspace"));
	m_toolBar->setIconSize(iconNewWorkspace.size());

	QObject::connect(actionNewWorkspace, SIGNAL(triggered()), this, SLOT(newWorkspace()));

	QStringList headerList;
	headerList << tr("Workspace");
	ui.treeWidget->setHeaderLabels(headerList);
}

CF_WorkspaceWindow::~CF_WorkspaceWindow()
{
	delete m_toolBar;
}

void CF_WorkspaceWindow::updated(CL_UpdatedContext* context)
{
	switch(context->reason())
	{
	case CF_UpdatedReason::NEW_WORKSPACE:
		break;
	case CF_UpdatedReason::NEW_SCENE:
		{
			//CF_NewSceneContext* param = static_cast<CF_NewSceneContext*>(context);
			reloadWorkspace();
		}
		break;
	}
}

void CF_WorkspaceWindow::newWorkspace()
{
	CF_NewWorkspaceDialog dlg;
	int ret = dlg.exec();
	if(ret==0)
		return;

	workspaceManager->createProject(dlg.getName(), dlg.getLocation());
	workspaceManager->save();
	reloadWorkspace();

	notifyUpdated(new CF_NewWorkspaceContext(dlg.getName()));
}

void CF_WorkspaceWindow::openWorkspace()
{
	QString filePath = QFileDialog::getOpenFileName(this, "Open Workspace", "", CF_WORKSPACE_FILE_FILTER);
	if(filePath.isEmpty())
		return;

	workspaceManager->load(filePath);
	reloadWorkspace();

	notifyUpdated(new CF_OpenWorkspaceContext(workspaceManager->getProjectName()));
}

void CF_WorkspaceWindow::reloadWorkspace()
{
	ui.treeWidget->clear();

	if(!workspaceManager->isLoaded())
		return;

	QTreeWidgetItem* newWorkspaceItem = new QTreeWidgetItem(ui.treeWidget);
	QTreeWidgetItem* newSceneGroupItem = new QTreeWidgetItem(newWorkspaceItem);
	newWorkspaceItem->setText(0, workspaceManager->getProjectName());
	newSceneGroupItem->setText(0, tr("Scenes"));
	for(int iScene=0; iScene<workspaceManager->getSceneCount(); iScene++)
	{
		CE_Scene* node = workspaceManager->getScene(iScene);
		QTreeWidgetItem* newSceneItem = new QTreeWidgetItem(newSceneGroupItem);
		newSceneItem->setText(0, tr(node->sceneName()) + "." CF_SCENE_FILE_EXT);
	}

	ui.treeWidget->expandAll();
}
